/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mail.server;

import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import mail.account.UserAccount;
import mail.attribute.MailItem;
import mail.general.FileUtils;

/**
 *
 * @author timoteo
 */
public class MailItemReader {

    public MailItem read(UserAccount account, File file) throws ParseException, IOException {
        final StringBuilder message = new StringBuilder();
        FileUtils.readFile(new FileReader(file), new FileUtils.FileBlock() {

            @Override
            public void processLine(String line) {
                message.append(line);
            }
        });
        String info[] = message.toString().split("[$]");
        MailItem item = new MailItem(info[1], account.toString(), info[3], info[4]);
        String filename = file.getName();
        item.setDate(new Date(Long.valueOf(filename.substring(0, filename.indexOf(".")))));
        if (info[0].equals("0")) {
            item.markAsRead();
        }
        readAttachments(item, file);
        return item;
    }

    private void readAttachments(MailItem item, final File file) {
        File folder = new File(file.getParentFile().getPath() + "/attachments/");
        if (folder.exists()) {
            File[] files = folder.listFiles(new FileFilter() {

                @Override
                public boolean accept(File childFile) {
                    return childFile.getName().startsWith(file.getName() + "_");
                }
            });
            for (File attachmentFile : files) {
                item.getMessage().attachFile(attachmentFile.getAbsolutePath());
            }
        }
    }
}
